<template>
  <div class="main-container">
    <div class="header">
      <div style="display: flex; align-items: center;">
        <el-icon size="24" style="margin-right: 10px;"><Monitor /></el-icon>
        <h2>设备管理系统</h2>
      </div>
      <div style="display: flex; align-items: center;">
        <span style="margin-right: 15px;">欢迎，{{ username }}</span>
        <el-button type="text" @click="handleLogout" style="color: white;">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>
    </div>
    
    <div class="content">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>{{ isEdit ? '编辑Modbus配置' : '添加Modbus配置' }}</h3>
        <el-button @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
      </div>
      
      <el-card style="max-width: 800px; margin: 0 auto;">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="150px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="编号" prop="keyNumber">
                <el-input-number v-model="form.keyNumber" :min="1" :max="999" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上报Key名称" prop="keyName">
                <el-input v-model="form.keyName" placeholder="请输入Key名称" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="从站地址" prop="slaveAddress">
                <el-input-number v-model="form.slaveAddress" :min="1" :max="255" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="读/写" prop="operationType">
                <el-radio-group v-model="form.operationType">
                  <el-radio :label="1">读</el-radio>
                  <el-radio :label="2">写</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="功能码" prop="functionCode">
                <el-select v-model="form.functionCode" placeholder="请选择功能码" style="width: 100%;" @change="handleFunctionCodeChange">
                  <el-option 
                    v-for="option in functionCodeOptions" 
                    :key="option.value" 
                    :label="option.label" 
                    :value="option.value" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="functionValueLabel" prop="functionValue">
                <el-input-number v-model="form.functionValue" :min="0" :max="99" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="寄存器起始地址" prop="registerStartAddress">
                <el-input-number v-model="form.registerStartAddress" :min="0" :max="65535" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="寄存器读取数量" prop="registerCount">
                <el-input-number v-model="form.registerCount" :min="1" :max="125" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="字节顺序" prop="byteOrder">
                <el-select v-model="form.byteOrder" placeholder="请选择字节顺序" style="width: 100%;">
                  <el-option label="大端" :value="1" />
                  <el-option label="小端" :value="2" />
                  <el-option label="中端" :value="3" />
                  <el-option label="混合端" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="倍率" prop="multiplier">
                <el-input-number v-model="form.multiplier" :min="-10000" :max="10000" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="loading">
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
            <el-button @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'DeviceKeyForm',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const loading = ref(false)
    const username = ref(sessionStorage.getItem('username') || '')
    const formRef = ref()
    const isEdit = ref(!!route.params.id)
    const subDeviceId = ref(route.params.subDeviceId)

    const form = reactive({
      keyNumber: 1,
      keyName: '',
      slaveAddress: 1,
      operationType: 1,
      functionCode: null,
      functionValue: 0,
      registerStartAddress: 0,
      registerCount: 1,
      byteOrder: 1,
      multiplier: 1,
      subDeviceId: subDeviceId.value
    })

    const rules = reactive({
      keyNumber: [
        { required: true, message: '请输入编号', trigger: 'blur' },
        { type: 'number', min: 1, max: 999, message: '编号应在1-999之间', trigger: 'blur' }
      ],
      keyName: [
        { required: true, message: '请输入Key名称', trigger: 'blur' },
        { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
      ],
      slaveAddress: [
        { required: true, message: '请输入从站地址', trigger: 'blur' },
        { type: 'number', min: 1, max: 255, message: '从站地址应在1-255之间', trigger: 'blur' }
      ],
      operationType: [
        { required: true, message: '请选择读写类型', trigger: 'change' }
      ],
      functionCode: [
        { required: true, message: '请选择功能码', trigger: 'change' }
      ],
      functionValue: [
        { required: true, message: '请输入功能值', trigger: 'blur' },
        { type: 'number', min: 0, max: 99, message: '功能值应在0-99之间', trigger: 'blur' }
      ],
      registerStartAddress: [
        { required: true, message: '请输入寄存器起始地址', trigger: 'blur' },
        { type: 'number', min: 0, max: 65535, message: '起始地址应在0-65535之间', trigger: 'blur' }
      ],
      registerCount: [
        { required: true, message: '请输入寄存器读取数量', trigger: 'blur' },
        { type: 'number', min: 1, max: 125, message: '读取数量应在1-125之间', trigger: 'blur' }
      ],
      byteOrder: [
        { required: true, message: '请选择字节顺序', trigger: 'change' }
      ],
      multiplier: [
        { required: true, message: '请输入倍率', trigger: 'blur' },
        { type: 'number', min: -10000, max: 10000, message: '倍率应在-10000到10000之间', trigger: 'blur' }
      ]
    })

    const loadDeviceKey = async () => {
      if (!isEdit.value) return
      
      try {
        loading.value = true
        const token = sessionStorage.getItem('token')
        const response = await axios.get(`/api/device-keys/${route.params.id}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data.success) {
          Object.assign(form, response.data.data)
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('加载Modbus配置信息失败')
      } finally {
        loading.value = false
      }
    }

    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        loading.value = true
        
        const token = sessionStorage.getItem('token')
        const headers = { Authorization: `Bearer ${token}` }
        
        let response
        if (isEdit.value) {
          response = await axios.put(`/api/device-keys/${route.params.id}`, form, { headers })
        } else {
          response = await axios.post('/api/device-keys', form, { headers })
        }
        
        if (response.data.success) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          handleBack()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error.response?.data?.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
        }
      } finally {
        loading.value = false
      }
    }

    const handleReset = () => {
      formRef.value.resetFields()
    }

    const handleBack = () => {
      if (isEdit.value) {
        router.push(`/device-keys/${form.subDeviceId}`)
      } else {
        router.push(`/device-keys/${subDeviceId.value}`)
      }
    }

    const handleLogout = () => {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('username')
      router.push('/login')
    }

    // 功能码选项
    const functionCodeOptions = computed(() => {
      if (form.operationType === 1) { // 读
        return [
          { label: '读线圈状态', value: 1 },
          { label: '读离散输入状态', value: 2 },
          { label: '读保持寄存器', value: 3 },
          { label: '读输入寄存器', value: 4 }
        ]
      } else { // 写
        return [
          { label: '写单个线圈', value: 5 },
          { label: '写单个保持寄存器', value: 6 },
          { label: '写多个线圈', value: 7 },
          { label: '写多个保持寄存器', value: 8 }
        ]
      }
    })

    // 动态标签
    const functionValueLabel = computed(() => {
      if (form.operationType === 1) {
        return '输入功能码'
      } else {
        return '输入功能码'
      }
    })

    // 功能码变化处理
    const handleFunctionCodeChange = () => {
      // 功能码变化时重置功能值
      form.functionValue = 0
    }

    // 监听操作类型变化
    watch(() => form.operationType, () => {
      // 操作类型变化时重置功能码和功能值
      form.functionCode = null
      form.functionValue = 0
    })

    onMounted(() => {
      if (isEdit.value) {
        loadDeviceKey()
      }
    })

    return {
      loading,
      username,
      formRef,
      isEdit,
      form,
      rules,
      functionCodeOptions,
      functionValueLabel,
      handleFunctionCodeChange,
      handleSubmit,
      handleReset,
      handleBack,
      handleLogout
    }
  }
}
</script>

<style scoped>
.main-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
  color: white;
  padding: 15px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.content {
  padding: 30px;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>